package com.shgsh.server.service;

import com.alibaba.fastjson.JSON;
import com.shgsh.server.message.Message;
import com.shgsh.server.model.IMSignal;
import com.shgsh.server.model.IMUser;
import com.shgsh.server.utils.ManageServerConClient;
import com.shgsh.server.utils.SecurityUtil;
import com.shgsh.server.utils.ServerConClientThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

/**
 * 服务端
 * Created by jessy on 2015/8/12.
 */

public class IMServerConnectService {
    Logger logger = LoggerFactory.getLogger(IMServerConnectService.class);

    IMUserService userService = new IMUserService();

    //是否连接上服务器
    boolean started = false;
    ServerSocket ss = null;
    Socket s = null;
    IMUser user = null;
    ObjectOutputStream oos = null;
    ObjectInputStream ois = null;
    final Object o = new Object();
    public /*synchronized*/ void start() {
        try {
            ss = new ServerSocket(8888);
            started = true;
            logger.debug(" connecting .... ");
        } catch (BindException e) {
            logger.debug("the port was used please restart server ");
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            while (started) {
                //进入
                s = ss.accept();

                String ip = s.getInetAddress().getHostAddress();
                int port = s.getPort();
                logger.debug("client ip and port are " + ip + " ," + s.getPort());
                Message message = null;
                ois = new ObjectInputStream(s.getInputStream());
                user = (IMUser) ois.readObject();
                //用户请求进入IM模块 判断存在该用户且该用户已登录且IP和port一致
                // （用户登录应用后，初始化user_data_table和user_specific_table表，字段sessionEncryptKey为“”）
                logger.debug("userservice --> " + userService);
                IMSignal userSignal = null;
                oos = new ObjectOutputStream(s.getOutputStream());
                //用户已存在且没有进入世界树模块（用户标识表中没有记录）
                if (userService.getUser(user.getId()) != null
                        && !ManageServerConClient.isOnline(user.getId())) {

                    logger.debug("user " + user.getId() + " enter ..... ");

                    //设置用户状态
                    user.setActiveState("0");
                    user.setLastEnterTime(new Date().toString());
                    userService.save(user);

                    userSignal = new IMSignal();
                    userSignal.setUserId(user.getId());
                    userSignal.setIpAndPort(ip + ":" + port);
                    //设置会话密钥
                    userSignal.setSessionEncryptKey(SecurityUtil.randomStrKey());
                    userService.saveIMSignal(userSignal);

                    //返回成功登录的信息包
                    message = new Message(true, "user enter worldtree success", user);

                    oos.writeObject(message);
                    //新起线程与客户端保持连接
                    ServerConClientThread cct = new ServerConClientThread(s);//单开一个线程，让该线程与该客户端保持连接
                    ManageServerConClient.addClientThread(user.getId(), cct);
                    cct.start();//启动与该客户端通信的线程


                } else {
                    logger.debug("fail.......");
                    message = new Message(false, "fail", user.toJson());
                    oos.writeObject(message);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (ss != null) {
                try {
                    ss.close();
                    //删除此次记录
                    userService.deleteSignalForUser(user.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


}

